﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using WenSkin.Controls;
using static WenSkin.WenJsonConfig.JsonConfig;

namespace WenSkin.WenJsonConfig
{
    public partial class WenConfigForm : WenSkin.Forms.WenForm
    {
        public WenConfigForm() : this("WenAutoConfig")
        {
        }
        public WenConfigForm(string jsonfilePath)
        {
            InitializeComponent();
            ControlAdd();
            Text += " - " + jsonfilePath;
            config = new JsonConfig(jsonfilePath);

            ConfigAdd();
        }
        
        public WenConfigForm(JsonConfig jsonConfig)
        {
            InitializeComponent();
            ControlAdd();
            Text += " - " + jsonConfig.JsonFileName;
            config = jsonConfig;

            ConfigAdd();
        }
        private readonly JsonConfig config;

        #region 公有属性

        public string SaveMessage { get; set; } = "保存成功！部分设置需要重启软件才能生效！";

        #endregion

        #region 委托事件

        [Category("Wen"), Description("按钮点击事件")]
        public event JsonConfigClickEventHandler JsonConfigItemClick;

        [Category("Wen"), Description("移除一项")]
        public event JsonConfigItemEventHandler JsonConfigItemRemove;

        [Category("Wen"), Description("新增一项")]
        public event JsonConfigItemEventHandler JsonConfigItemAdd;

        [Category("Wen"), Description("值变化")]
        public event JsonConfigItemValueEventHandler JsonConfigItemValueChanged;
        
        [Category("Wen"), Description("保存信息")]
        public event JsonConfigEventHandler JsonConfigSaveChanged;



        [ComVisible(true)]
        public delegate void JsonConfigClickEventHandler(object sender, JsonConfigItemClickEventArgs e);
        public class JsonConfigItemClickEventArgs : JsonConfigItemEventArgs
        {
            public JsonConfigItemClickEventArgs(bool showTextBox, JsonConfigGroup configXmlGroup, JsonConfigItem configXmlItem) : base(configXmlGroup, configXmlItem)
            {
                ShowTextBox = showTextBox;
                ConfigXmlGroup = configXmlGroup;
                ConfigXmlItem = configXmlItem;
            }

            public bool ShowTextBox { get; set; }
        }

        [ComVisible(true)]
        public delegate void JsonConfigItemValueEventHandler(object sender, JsonConfigItemValueEventArgs e);
        public class JsonConfigItemValueEventArgs : JsonConfigItemEventArgs
        {
            public JsonConfigItemValueEventArgs(JsonConfigGroup configXmlGroup, JsonConfigItem configXmlItem, string changeValue) : base(configXmlGroup, configXmlItem)
            {
                ChangeValue = changeValue;
                State = true;
            }
            public string ChangeValue { get; set; }
            public bool State { get; set; }
        }

        [ComVisible(true)]
        public delegate void JsonConfigItemEventHandler(object sender, JsonConfigItemEventArgs e);
        public class JsonConfigItemEventArgs : EventArgs
        {
            public JsonConfigItemEventArgs(JsonConfigGroup configXmlGroup, JsonConfigItem configXmlItem)
            {
                ConfigXmlGroup = configXmlGroup;
                ConfigXmlItem = configXmlItem;
            }
            public JsonConfigGroup ConfigXmlGroup { get; set; }
            public JsonConfigItem ConfigXmlItem { get; set; }
        }              
        
        [ComVisible(true)]
        public delegate void JsonConfigEventHandler(object sender, JsonConfigEventArgs e);
        public class JsonConfigEventArgs : EventArgs
        {
            private readonly JsonConfig configXmlParsing;

            public JsonConfigEventArgs(JsonConfig configXmlParsing)
            {
                this.configXmlParsing = configXmlParsing;
            }

            public JsonConfig ConfigXmlParsing => configXmlParsing;
        }
        #endregion

        private void ControlAdd()
        {
            WenButton WenImageButton = new WenButton()
            {
                Text = "保存",
                Dock = DockStyle.Bottom,
            };
            WenImageButton.Click += WenImageButton_Click;
            this.Controls.Add(WenImageButton);
        }

        private void WenImageButton_Click(object sender, EventArgs e)
        {
            SaveXmlConfig();
            MsgBoxInformation(SaveMessage);
        }
        /// <summary>
        /// 保存设置
        /// </summary>
        public void SaveXmlConfig()
        {
            config.Save();
            JsonConfigSaveChanged?.Invoke(this, new JsonConfigEventArgs(this.config));
        }

        private void ConfigAdd()
        {
            flowLayoutPanel1.Controls.Clear();

            ControlsAdd(flowLayoutPanel1,config.Groups);


            void ControlsAdd(Control owner,JsonConfigGroupList groups)
            {
                foreach (var gr in groups)
                {
                    GroupBox groupBox = new GroupBox()
                    {
                        Name = gr.Name,
                        Text = gr.Info,
                        AutoSize = true,
                        BackColor = Color.Transparent,
                        ForeColor = WenSkin.Controls.ControlHelper.ColorReverse(this.BackColor),
                        Visible = gr.Visible,
                    };
                    FlowLayoutPanel flow = new FlowLayoutPanel()
                    {
                        Dock = DockStyle.Fill,
                        Size = new Size(450, 0),
                        AutoSize = true,
                        FlowDirection = FlowDirection.TopDown
                    };
                    groupBox.Controls.Add(flow);
                    foreach (var item in gr.Items)
                    {
                        JsonConfigItemControl configXmlItemControl = new JsonConfigItemControl(gr, item);
                        configXmlItemControl.JsonConfigItemClick += (s, e) =>
                        {
                            //事件准发即可
                            JsonConfigItemClick?.Invoke(this, e);
                        };
                        configXmlItemControl.JsonConfigItemRemove += (s, e) =>
                        {
                            //移除内容界面需要更改，做处理
                            JsonConfigItemRemove?.Invoke(this, e);
                            gr.Items.Remove(item);
                            config.Save();
                            ConfigAdd();
                        };
                        configXmlItemControl.JsonConfigItemValueChanged += (s, e) =>
                        {
                            JsonConfigItemValueChanged?.Invoke(this, e);
                        };
                        flow.Controls.Add(configXmlItemControl);
                    }
                    //添加按钮
                    if (gr.AllowAdd)
                    {
                        flow.Controls.Add(AllowAddButton(gr));
                    }
                    if (gr.Groups.Count > 0)
                        ControlsAdd(flow, gr.Groups);

                    owner.Controls.Add(groupBox);
                }
            }

            
        }

        #region 增添一个添加一项按钮
        private WenButton AllowAddButton(JsonConfigGroup group)
        {
            WenButton button = new WenButton()
            {
                Text = "新增一项",
                Size = new Size(500, 26)
            };
            button.Click += (s, e) =>
            {
                JsonConfigItem configXmlItem = new JsonConfigItem(group.Items)
                {
                    Name = $"{group.Name}{group.Items.Count + 1}",
                    Info = "自动添加",
                    Ecc = false,
                    ReadOnly = false,
                    Delete = true,
                    Value = "",
                };

                WenSkin.Forms.WenForm form = new Forms.WenForm()
                {
                    StartPosition = FormStartPosition.CenterScreen,
                    Size = new Size(300, 100),
                    Text = "请输入名称"
                };

                TextBox textBox = new TextBox()
                {
                    Text = "新增名称",
                    Dock = DockStyle.Fill,
                    //Multiline = true,
                    ScrollBars = ScrollBars.Both,
                    WordWrap = false
                };

                WenButton button1 = new WenButton()
                {
                    Text = "确定",
                    Dock = DockStyle.Bottom,
                };
                button1.Click += (sx, ex) =>
                {
                    JsonConfigItemAdd?.Invoke(this, new JsonConfigItemEventArgs(group, configXmlItem));
                    configXmlItem.Info = textBox.Text;
                    group.Items.Add(configXmlItem);
                    config.Save();
                    form.Dispose();
                    ConfigAdd();
                };

                form.Controls.Add(textBox);
                form.Controls.Add(button1);
                form.ShowDialog();
            };
            return button;
        }

        #endregion

        #region 单项样式

        [ToolboxItem(false)]
        private class JsonConfigItemControl : WenControl
        {
            public JsonConfigItemControl(JsonConfigGroup gr, JsonConfigItem item) : base()
            {
                this.Visible = item.Visible;

                if (item.ComboBox)
                {
                    WenLableComboBox comboBox = new WenLableComboBox()
                    {
                        Dock = DockStyle.Fill,
                        Name = item.Name,
                        TextLable = item.Info,
                        DropDownStyle = item.ReadOnly ? ComboBoxStyle.DropDownList : ComboBoxStyle.DropDown,
                    };
                    comboBox.Items.AddRange(item.Items.ToArray());
                    comboBox.Text = item.Value?.ToString();

                    if (item.Tip != null && item.Tip.Length != 0)
                    {
                        foreach (Control c in comboBox.Controls)
                        {
                            tip.SetToolTip(c, item.Tip);
                        }
                    }

                    comboBox.TextChanged += (s, e) =>
                    {
                        //值改变响应事件
                        JsonConfigItemValueEventArgs configXmlItemValueEventArgs = new JsonConfigItemValueEventArgs(gr, item, comboBox.Text);
                        JsonConfigItemValueChanged?.Invoke(this, configXmlItemValueEventArgs);

                        if (configXmlItemValueEventArgs.State)
                            item.Value = comboBox.Text;
                    };

                    comboBox.Size = new Size(450, comboBox.Height);
                    this.Controls.Add(comboBox);

                    //移除项目 按钮
                    if (gr.AllowAdd && item.Delete)
                    {
                        WenButton button = new WenButton()
                        {
                            Image = Properties.Resources.close,
                            ImageSize = new Size(16, 16),
                            Dock = DockStyle.Right,
                            Size = new Size(20, 20)
                        };
                        button.Click += (s, e) =>
                        {
                            if (this.MsgBoxAsterisk("删除不可逆，是否删除"))
                            {
                                JsonConfigItemRemove?.Invoke(this, new JsonConfigItemEventArgs(gr, item));
                            }
                        };
                        this.Controls.Add(button);
                    }
                    this.Size = new Size(500, comboBox.Height + 3);
                }
                else
                {
                    WenLableTextBox textBox = new WenLableTextBox()
                    {
                        Dock = DockStyle.Fill,
                        Name = item.Name,
                        TextLable = item.Info,
                        Text = item.Value?.ToString(),
                        Password = item.Ecc,
                        ReadOnly = item.ReadOnly,
                    };
                    //按钮点击事件
                    textBox.ButtonClick += (s, e) =>
                    {
                        JsonConfigItemClickEventArgs ex = new JsonConfigItemClickEventArgs(e.ShowTextBox, gr, item);
                        JsonConfigItemClick?.Invoke(this, ex);
                        e.ShowTextBox = ex.ShowTextBox;
                    };
                    if (item.Tip != null && item.Tip.Length != 0)
                    {
                        foreach (Control c in textBox.Controls)
                        {
                            tip.SetToolTip(c, item.Tip);
                        }
                    }

                    textBox.Size = new Size(450, textBox.Height);
                    textBox.TextBeforeChanged += (s, e) =>
                    {
                        //值改变响应事件
                        JsonConfigItemValueEventArgs configXmlItemValueEventArgs = new JsonConfigItemValueEventArgs(gr, item, textBox.Text);

                        JsonConfigItemValueChanged?.Invoke(this, configXmlItemValueEventArgs);

                        e.State = configXmlItemValueEventArgs.State;
                        if (configXmlItemValueEventArgs.State)
                            item.Value = textBox.Text;
                    };
                    this.Controls.Add(textBox);

                    //移除项目 按钮
                    if (gr.AllowAdd && item.Delete)
                    {
                        WenButton button = new WenButton()
                        {
                            Image = Properties.Resources.close,
                            ImageSize = new Size(16, 16),
                            Dock = DockStyle.Right,
                            Size = new Size(20, 20)
                        };
                        button.Click += (s, e) =>
                        {
                            if (this.MsgBoxAsterisk("删除不可逆，是否删除"))
                            {
                                JsonConfigItemRemove?.Invoke(this, new JsonConfigItemEventArgs(gr, item));
                            }
                        };
                        this.Controls.Add(button);
                    }
                    this.Size = new Size(500, textBox.Height);
                }
            }

            #region 私有属性

            private readonly ToolTip tip = new ToolTip();

            #endregion

            #region 委托事件

            [Category("Wen"), Description("按钮点击事件")]
            public event JsonConfigClickEventHandler JsonConfigItemClick;

            [Category("Wen"), Description("移除一项")]
            public event JsonConfigItemEventHandler JsonConfigItemRemove;

            [Category("Wen"), Description("值变化")]
            public event JsonConfigItemValueEventHandler JsonConfigItemValueChanged;

            #endregion
        }
        #endregion
    }
}
